import {Component, EventEmitter, forwardRef, Input, OnChanges, OnInit, Output, SimpleChanges} from '@angular/core';
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from '@angular/forms';
import {DatePipe} from "@angular/common";

@Component({
  selector: 'app-date-picker',
  template: `
    <nz-date-picker  [(ngModel)]="model" [name]="name" (ngModelChange)="modelChange($event)" ></nz-date-picker>
    `,
  providers: [{
    provide: NG_VALUE_ACCESSOR,
    useExisting: forwardRef(() => DatePickerComponent),
    multi: true
  }],
  styleUrls: ['./index.less']
})
export class DatePickerComponent implements OnInit, ControlValueAccessor, OnChanges {
  model: any;
  @Input() name;
  @Input() nzFormat='yyyy-MM-dd HH:mm:ss';
  @Output() ngModelChange = new EventEmitter();
  public onModelChange: any = () => { };
  public onModelTouched: any = () => { };
  writeValue(value: any) {
    if (value){
      this.model = new Date(value);
    }
  }
  registerOnChange(fn: any): void {
    this.onModelChange = fn;
  }
  registerOnTouched(fn: any): void {
    this.onModelTouched = fn;
  }

  modelChange(value) {
    this.model = value;
    value=this.datePipe.transform(value,this.nzFormat)
    this.ngModelChange.emit(value);
  }

  constructor(  private datePipe:DatePipe) { }
  ngOnInit(): void {
   
  }
  ngOnChanges(changes: SimpleChanges) {
   /* console.log(this.modal)
    console.log(changes)*/
  }

}
